package com.tyk.bookstore.back.message.mq;

import com.rabbitmq.client.Channel;
import com.tyk.bookstore.back.common.mq.RabbitManager;
import com.tyk.bookstore.back.message.model.entity.InfoNoticeDo;
import com.tyk.bookstore.back.message.model.entity.ServiceNoticeDo;
import com.tyk.bookstore.back.message.model.enume.NoticeState;
import com.tyk.bookstore.back.message.repository.InfoNoticeRepository;
import com.tyk.bookstore.back.message.repository.ServiceNoticeRepository;
import com.tyk.bookstore.back.message.service.InfoNoticeService;
import com.tyk.bookstore.back.message.service.ServiceNoticeService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author tyk
 * @description NoticeMqReceiver
 */
@Service
@RequiredArgsConstructor
public class NoticeMqReceiver {

    /**
     * 消息唯一标识的key
     */
    @Value("${mine.mq.rabbit.id-key}")
    private String idKey;


    /**
     * 默认重试次数
     */
    @Value("${mine.mq.rabbit.retry}")
    public int retryCount;

    /**
     * 重试次数的key
     */
    @Value("${mine.mq.rabbit.args.retry-count}")
    private String retryCountKey;

    private final InfoNoticeService infoNoticeService;
    private final InfoNoticeRepository infoNoticeRepository;
    private final ServiceNoticeService serviceNoticeService;
    private final ServiceNoticeRepository serviceNoticeRepository;
    private final RabbitManager rabbitManager;

    /**
     * 定时发布消息通知
     *
     * @param noticeId 消息通知ID
     * @param msg      消息
     * @param channel  通道
     */
    @SneakyThrows
    @RabbitListener(queues = NoticeMqConstant.NOTICE_INFO_RELEASE_QUEUE)
    public void receiveInfoNoticeDelayMsg(Long noticeId, Message msg, Channel channel) {
        MessageProperties ps = msg.getMessageProperties();
        try {
            // 将消息状态修改为已发布
            if (infoNoticeRepository.exist1Eq(
                    InfoNoticeDo::getId, noticeId, InfoNoticeDo.class
            )) infoNoticeService.changeState(noticeId, NoticeState.ON);
        } catch (Exception e) {
            // 写日志，通知维护人员
            System.out.println("消息通知发布失败, id=" + noticeId);

            // 查看是否可以重试
            int count = this.retryCount;
            String rcs = ps.getHeader(this.retryCountKey);
            if (rcs != null) count = Integer.parseInt(rcs);

            // 转非延迟消息进行重试
            if (count > 0) {
                rabbitManager.sendMsg(
                        ps.getReceivedExchange(),
                        ps.getReceivedRoutingKey(),
                        noticeId,
                        ps.getHeader(this.idKey),
                        Map.of(
                                NoticeMqConstant.ARGS_MEMBER_ID, ps.getHeader(NoticeMqConstant.ARGS_MEMBER_ID),
                                this.retryCountKey, String.valueOf(--count)
                        )
                );
            } else {
                System.out.println("消息通知发布重试失败, id=" + noticeId);
            }
        }
        // 确认消息已被消费
        // 无论是否成功处理，此消息确已被消费者成功接收
        channel.basicAck(ps.getDeliveryTag(), false);
    }

    /**
     * 定时发布消息通知
     *
     * @param noticeId 消息通知ID
     * @param msg      消息
     * @param channel  通道
     */
    @SneakyThrows
    @RabbitListener(queues = NoticeMqConstant.NOTICE_SERVICE_RELEASE_QUEUE)
    public void receiveServiceNoticeDelayMsg(Long noticeId, Message msg, Channel channel) {
        MessageProperties ps = msg.getMessageProperties();
        try {
            // 将消息状态修改为已发布
            if (serviceNoticeRepository.exist1Eq(
                    ServiceNoticeDo::getId, noticeId, ServiceNoticeDo.class
            )) serviceNoticeService.changeState(noticeId, NoticeState.ON);
        } catch (Exception e) {

            // 写日志，通知维护人员
            System.out.println("服务通知发布失败, id=" + noticeId);

            // 查看是否可以重试
            int count = this.retryCount;
            String rcs = ps.getHeader(this.retryCountKey);
            if (rcs != null) count = Integer.parseInt(rcs);

            // 转非延迟消息进行重试
            if (count > 0) {
                rabbitManager.sendMsg(
                        ps.getReceivedExchange(),
                        ps.getReceivedRoutingKey(),
                        noticeId,
                        ps.getHeader(this.idKey),
                        Map.of(
                                NoticeMqConstant.ARGS_MEMBER_ID, ps.getHeader(NoticeMqConstant.ARGS_MEMBER_ID),
                                this.retryCountKey, String.valueOf(--count)
                        )
                );
            } else {
                System.out.println("服务通知发布重试失败, id=" + noticeId);
            }
        }
        // 确认消息已被消费
        // 无论是否成功处理，此消息确已被消费者成功接收
        channel.basicAck(ps.getDeliveryTag(), false);
    }

}
